package impexp;

import impexp.exportfile.IExportFile;
import impexp.importfile.IDataAnaly;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.json.JSONArray;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import com.aote.rs.mapper.WebException;
import com.aote.util.ExcelUtil;

public class FileManager {

	@SuppressWarnings("resource")
	public JSONArray read(String filepath) {
		// 拿到文件名
		InputStream is;
		try {
			is = new FileInputStream(new File(filepath));
		} catch (FileNotFoundException e) {
			throw new WebException(500, "您所选的文件不存在!!!");
		}
		filepath = filepath.replace("\\", "/");
		String fileName = filepath.split("/")[filepath.split("/").length - 1];

		List<String[]> data = null;
		if (fileName.endsWith("xls") || fileName.endsWith("xlsx")) {
			try {
				data = ExcelUtil.readExcel(is, fileName);
			} catch (IOException e) {
				throw new WebException(500, "文件解析错误!!!");
			}
		} else {
			throw new WebException(500, "非excel文件暂时未作处理.如有需求,请联系开发人员!!!!");
		}

		return getBean(fileName).analy(data);
	}

	public JSONArray export(String condition, String beanName) {
		try {
			return getExportBean(beanName).exportFile(condition);
		} catch (Exception e) {
			throw new WebException(500, e.getMessage());
		}
	}

	private IDataAnaly getBean(String fileName) {
		// 获取filename以下划线分割第一个
		String name = fileName.split("_")[0];
		WebApplicationContext wac = ContextLoader
				.getCurrentWebApplicationContext();
		return (IDataAnaly) wac.getBean(name);
	}

	private IExportFile getExportBean(String name) {
		// 获取filename以下划线分割第一个
		WebApplicationContext wac = ContextLoader
				.getCurrentWebApplicationContext();
		return (IExportFile) wac.getBean(name);
	}
}
